/*
 *  (C) Copyright 2008 Insula Tecnologia da Informacao Ltda.
 * 
 *  This file is part of Vulcano.
 *
 *  Vulcano is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Vulcano is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Vulcano.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.openinsula.vulcano.flex.controller;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.openinsula.vulcano.flex.controller.annotations.LazySafeController;
import org.openinsula.vulcano.orm.command.transaction.DaoCommandTransactionFacade;
import org.openinsula.vulcano.orm.command.transaction.InitializeCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@LazySafeController
@Component("lazyAssociationLoader")
public class VulcanoLazyAssociationLoader implements LazyAssociationLoader {
	protected final Log logger = LogFactory.getLog(getClass());

	@Autowired
	private DaoCommandTransactionFacade transactionFacade;

	@Override
	public <T> T initialize(final T instance) {
		return initialize(instance, null);
	}

	@Override
	public <T> T initialize(final T instance, final String associationName) {
		InitializeCallback<T> initializeCallback = null;

		if (StringUtils.hasText(associationName)) {
			initializeCallback = new InitializeCallback<T>() {

				@Override
				public void initialize(final T obj) {
					try {
						Hibernate.initialize(PropertyUtils.getProperty(obj, associationName));
					}
					catch (Exception e) {
						if (logger.isWarnEnabled()) {
							logger.warn(e.getMessage());
						}
					}
				}

			};
		}

		transactionFacade.refresh(initializeCallback, instance);

		return instance;
	}

}
